package org.mall.modules.product.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.mall.common.api.vo.CommonResult;
import org.mall.common.api.vo.Result;
import org.mall.common.constant.AppMessageTypeEnum;
import org.mall.common.constant.CommonStatusEnum;
import org.mall.common.constant.ProductSpuConstants;
import org.mall.common.system.query.QueryGenerator;
import org.mall.common.system.util.JwtUtil;
import org.mall.common.util.DateUtils;
import org.mall.common.util.GeneratorSnowFlakeIDUtils;
import org.mall.common.util.ObjectUtils;
import org.mall.common.util.json.JacksonUtils;
import org.mall.common.util.oConvertUtils;
import org.mall.convert.product.CommoditySpuConvert;
import org.mall.modules.message.service.AppMessageService;
import org.mall.modules.order.service.OrderService;
import org.mall.modules.pojo.common.AppMessageDTO;
import org.mall.modules.pojo.product.dto.*;
import org.mall.modules.pojo.product.vo.commodity.*;
import org.mall.modules.pojo.promotion.bo.ProductRecommendBO;
import org.mall.modules.pojo.shop.ShopCategoryDTO;
import org.mall.modules.pojo.shop.ShopDTO;
import org.mall.modules.product.entities.CommoditySku;
import org.mall.modules.product.entities.CommoditySpu;
import org.mall.modules.product.entities.ProductMsg;
import org.mall.modules.product.service.ICommoditySkuService;
import org.mall.modules.product.service.ICommoditySpuService;
import org.mall.modules.promotion.service.ProductRecommendService;
import org.mall.modules.seller.entity.Seller;
import org.mall.modules.shop.service.RpcShopCategoryRelationshipService;
import org.mall.modules.shop.service.RpcShopCategoryService;
import org.mall.modules.shop.service.ShopService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 商品SPU
 * @Author: jeecg-boot
 * @Date:   2019-11-07
 * @Version: V1.0
 */
@RestController
@RequestMapping("/goodsMain")
@Slf4j
public class CommodityController {
    @Autowired
    private ICommoditySpuService iCommoditySpuService;
    @Autowired
    private ICommoditySkuService iCommoditySkuService;
    private final String spuVisible="1";
    private final String splitFlag=",";

    @Autowired
    private OrderService orderService;

   @Autowired
   RpcShopCategoryRelationshipService relationshipService;

   @Autowired
   RpcShopCategoryService categoryService;
    @Autowired
    private ProductRecommendService productRecommendService;



   @Autowired
   ShopService shopService;

    @Autowired
    AppMessageService appMessageService;
    /**
     * web 查询商品分页列表查询
     * @param commoditySpuDTO
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @GetMapping(value = "/list")
    public Result<?> queryPageList(CommoditySpuDTO commoditySpuDTO,
                                          @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                          @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                          HttpServletRequest req) {
        Result<IPage<?>> result = new Result<>();
        QueryWrapper<CommoditySpu> queryWrapper = QueryGenerator.initQueryWrapper(ObjectUtils.copyObject(commoditySpuDTO,CommoditySpu.class), req.getParameterMap());
        Page<CommoditySpu> page = new Page(pageNo, pageSize);
        //增加判断条件，查询未删除的
        queryWrapper.eq("deleted",0);
        IPage<CommoditySpu> pageList = iCommoditySpuService.page(page, queryWrapper);
        if(pageList==null){
            return   Result.error("没有数据");
        }
        //所有店铺ids
        List<String> shopIds=pageList.getRecords().stream().map(CommoditySpu::getShopId).collect(Collectors.toList());
        //通过店铺ids 获取店铺名称
        CommonResult<List<ShopDTO>> shopNames= shopService.getShopInfoById(shopIds);
        Page ipage=new Page();
        result.setSuccess(true);
        result.setResult(pageList);
        BeanUtils.copyProperties(pageList,ipage);
        ipage.setRecords(pageList.getRecords().stream()
                .map(a->ObjectUtils.copyObject(a,CommoditySpuDTO.class)
                        .setShopName(shopNames.getData().stream()
                                .filter(shopDTO -> shopDTO.getId().equals(a.getShopId())).
                                        map(ShopDTO::getShopName)
                                .findFirst().orElse(""))).collect(Collectors.toList()));
        return Result.ok(ipage);
    }
    /***
     * web端待审核列表页面接口
     * */
    @GetMapping(value = "/webto/list")
    public Result<?> queryWebtPageList(CommoditySpuDTO commoditySpuDTO,
                                       @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                       @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                       HttpServletRequest req) {
        QueryWrapper<CommoditySpu> queryWrapper = QueryGenerator.initQueryWrapper(ObjectUtils.copyObject(commoditySpuDTO
                ,CommoditySpu.class), req.getParameterMap());
        Page page = new Page(pageNo, pageSize);
        //增加判断条件，查询未删除的
        queryWrapper.eq("deleted",0);
        //增加判断条件，查询待审核
        queryWrapper.in("to_examine","0","2");
        IPage<CommoditySpu> pageList = iCommoditySpuService.page(page, queryWrapper);
        if(pageList==null){
            return   Result.error("没有数据");
        }
        //所有店铺ids
        List<String> shopIds=pageList.getRecords().stream().map(CommoditySpu::getShopId).collect(Collectors.toList());
        //通过店铺ids 获取店铺名称
        CommonResult<List<ShopDTO>> shopNames= shopService.getShopInfoById(shopIds);
        Page ipage=new Page();
        BeanUtils.copyProperties(pageList,ipage);
        ipage.setRecords(pageList.getRecords().stream()
                .map(a->ObjectUtils.copyObject(a,CommoditySpuDTO.class)
                        .setShopName(shopNames.getData().stream()
                                .filter(shopDTO -> shopDTO.getId().equals(a.getShopId())).
                                        map(ShopDTO::getShopName)
                                .findFirst().orElse(""))).collect(Collectors.toList()));
        return Result.ok(ipage);
    }

    @GetMapping(value = "/web/list")
    public Result<?> queryWebPageList(CommoditySpuDTO commoditySpuDTO,
                                      @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                      @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                      HttpServletRequest req) {
        CommoditySpu spu=new CommoditySpu();
        BeanUtils.copyProperties(commoditySpuDTO,spu);
        QueryWrapper<CommoditySpu> queryWrapper = QueryGenerator.initQueryWrapper(spu, req.getParameterMap());
        Page page = new Page(pageNo, pageSize);
        //增加判断条件，查询未删除的
        queryWrapper.eq("deleted",0);
        //增加判断条件，查询审核通过的
        queryWrapper.eq("to_examine","1");
        IPage<CommoditySpu> pageList = iCommoditySpuService.page(page, queryWrapper);
        if(pageList==null){
          return   Result.error("没有数据");
        }
        //所有店铺ids
        List<String> shopIds=pageList.getRecords().stream().map(CommoditySpu::getShopId).collect(Collectors.toList());
        //通过店铺ids 获取店铺名称

        CommonResult<List<ShopDTO>> result= shopService.getShopInfoById(shopIds);
        List<ShopDTO> shopNames;
        if (result.isSuccess()){
            shopNames=result.getData();
        }else {
            shopNames=new ArrayList<>();
        }
        Page ipage=new Page();
        BeanUtils.copyProperties(pageList,ipage);
        ipage.setRecords(pageList.getRecords().stream()
                .map(a->{
                    CommoditySpuDTO temp=new CommoditySpuDTO();
                    BeanUtils.copyProperties(a,temp);
                     return    temp.setShopName(shopNames.stream()
                                .filter(shopDTO -> shopDTO.getId().equals(a.getShopId())).
                                        map(ShopDTO::getShopName)
                                .findFirst().orElse(""));}).collect(Collectors.toList()));
        return Result.ok(ipage);
    }

    /**
     *   商户添加商品        BeanUtils.copyProperties(goodsMain,  commoditySpuDTO);
     * @param
     * @return
     */
    @PostMapping(value = "/merchant/add")
    public Result<CommoditySpuVO> add(@Valid @RequestBody CommoditySpuAddDTO spuVO, BindingResult bindingResult) {
        Result<CommoditySpuVO> result = new Result<CommoditySpuVO>();
        if(bindingResult.hasErrors()){
            return result.error500(JacksonUtils.toJSONString(bindingResult.getAllErrors()));
        }
        CommoditySpu spu = new CommoditySpu();
        BeanUtils.copyProperties(spuVO,spu);
        initProductSpu(spu);
        List<CommoditySku> skus =CommoditySpuConvert.INSTANCE.convert4(spuVO.getProductSkuList());
        initProductSku(skus,spu.getId());
        merchantAddSpu(spuVO, spu, skus);
        result.success("添加成功！");
        return result;
    }
    /**
     *   管理员添加商品        BeanUtils.copyProperties(goodsMain,  commoditySpuDTO);
     * @param
     * @return
     */
    @PostMapping(value = "/web/add")
    public Result<CommoditySpuVO> addWeb(@Valid @RequestBody CommoditySpuAddDTO spuVO, BindingResult bindingResult) {
        Result<CommoditySpuVO> result = new Result<CommoditySpuVO>();
        if(bindingResult.hasErrors()){
            return result.error500(JacksonUtils.toJSONString(bindingResult.getAllErrors()));
        }
        CommoditySpu spu = new CommoditySpu();
        BeanUtils.copyProperties(spuVO,spu);
        initProductWebSpu(spu);
        List<CommoditySku> skus =CommoditySpuConvert.INSTANCE.convert4(spuVO.getProductSkuList());
        initProductSku(skus,spu.getId());
        merchantAddSpu(spuVO, spu, skus);
        result.success("添加成功！");
        return result;
    }
    @Transactional
    public void merchantAddSpu(CommoditySpuAddDTO spuVO, CommoditySpu spu, List<CommoditySku> skus) {
        iCommoditySpuService.saveMain(spu, skus);
        if (spuVO.getEntryId()!=null){
            relationshipService.saveOneCategoryAndSpuId(spu.getId(),spuVO.getEntryId(),spu.getShopId());

        }
    }

    /**
     *  编辑
     * @return
     */
    @PostMapping(value = "/merchant/edit")
    @Transactional
    public Result<?> edit(@Valid @RequestBody CommoditySpuUpdateDTO commoditySpuUpdateDTO, BindingResult bindingResult) {
        Result<CommoditySpuVO> result = new Result<CommoditySpuVO>();
        if(bindingResult.hasErrors()){
            return result.error500(JacksonUtils.toJSONString(bindingResult.getAllErrors()));
        }

        CommoditySpu spu = iCommoditySpuService.getById(commoditySpuUpdateDTO.getId());

        if (spu.getDeleted()){
            return Result.error("商品不存在");
        }
        if (spu.getVisible()){
            return Result.error("商品处于上架状态");
        }
//        CommoditySpu spuDb=CommoditySpuConvert.INSTANCE.convert5(commoditySpuUpdateDTO);
        CommoditySpu spuDb= new CommoditySpu();
        BeanUtils.copyProperties(commoditySpuUpdateDTO,spuDb);
        List<CommoditySku> skuList=CommoditySpuConvert.INSTANCE.convert4(commoditySpuUpdateDTO.getProductSkuList());
        initProductSku(skuList,spuDb.getId());
        saveMerchantEditResult(commoditySpuUpdateDTO, spuDb, skuList);
        return result;
    }
    @Transactional
    public void saveMerchantEditResult(CommoditySpuUpdateDTO commoditySpuVO, CommoditySpu spuDb, List<CommoditySku> skuList) {
        relationshipService.deleteOneCategoryAndSpuId(commoditySpuVO.getId());
        if (commoditySpuVO.getEntryId()!=null){
            relationshipService.saveOneCategoryAndSpuId(commoditySpuVO.getId(), commoditySpuVO.getEntryId(), commoditySpuVO.getShopId());
        }
        iCommoditySpuService.updateMain(spuDb, skuList);
    }

    /**
     * 管理端编辑商品
     * @param commoditySpuUpdateDTO
     * @param bindingResult
     * @return
     */
    @PutMapping(value = "/web/edit")
    public Result<?> editWeb(@Valid @RequestBody CommoditySpuUpdateDTO commoditySpuUpdateDTO, BindingResult bindingResult) {
        Result<CommoditySpuVO> result = new Result<CommoditySpuVO>();
        if(bindingResult.hasErrors()){
            return result.error500(JacksonUtils.toJSONString(bindingResult.getAllErrors()));
        }

        CommoditySpu spu = iCommoditySpuService.getById(commoditySpuUpdateDTO.getId());

        if (spu.getDeleted()){
            return Result.error("商品不存在");
        }
        if (spu.getVisible()){
            return Result.error("商品处于上架状态");
        }
//        CommoditySpu spuDb=CommoditySpuConvert.INSTANCE.convert5(commoditySpuUpdateDTO);
        CommoditySpu spuDb= new CommoditySpu();
        BeanUtils.copyProperties(commoditySpuUpdateDTO,spuDb);
        List<CommoditySku> skuList=CommoditySpuConvert.INSTANCE.convert4(commoditySpuUpdateDTO.getProductSkuList());
        initProductSku(skuList,spuDb.getId());
        saveMerchantEditResult(commoditySpuUpdateDTO, spuDb, skuList);
        return result;
    }

    /**
     *   通过id删除 spuid
     * @param commoditySpuDTO
     * @return
     */
    @PostMapping (value = "/merchant/delete")
    public Result<?> delete(@RequestBody CommoditySpuDTO commoditySpuDTO) {
        Result<Seller> result = new Result<Seller>();
        if(StringUtils.isBlank(Long.toString(commoditySpuDTO.getId()))){
            return result.error500("参数错误,id为空");
        }
        CommoditySpu db=iCommoditySpuService.getById(commoditySpuDTO.getId());
//		商品已上架执行删除操作(true (1):上架， false (0) 下架状态)
        if (db==null){
            return Result.error("商品不存在");
        }
        if(!db.getVisible()){
                iCommoditySpuService.delOneMain(commoditySpuDTO.getId());
                //删除商品id与类目id
                relationshipService.deleteOneCategoryAndSpuId(commoditySpuDTO.getId());
            result.success("删除成功!");
        }else {
            result.error500("商品处于上架状态，不能执行删除操作!");
        }
        return result;
    }
    @DeleteMapping (value = "/web/delete")
    public Result<?> deleteWeb(@RequestParam(name="id",required=true) Long id) {
        Result<Seller> result = new Result<Seller>();
        if(StringUtils.isBlank(Long.toString(id))){
            return result.error500("参数错误,id为空");
        }
        CommoditySpu db=iCommoditySpuService.getById(id);
//		商品已上架执行删除操作(true (1):上架， false (0) 下架状态)
        if(null!=db&&!db.getVisible()){
            try {
                iCommoditySpuService.delOneMain(id);
                //删除商品id与类目id
                relationshipService.deleteOneCategoryAndSpuId(id);
            } catch (Exception e) {
                log.error("删除失败",e.getMessage());
                result.error500("删除失败!");
            }
            result.success("删除成功!");
        }else {
            result.error500("商品已上架不能执行删除操作!");
        }
        return result;
    }

    /**
     *  批量删除--通过id删除1
     * @param
     * @return
     */
    @PostMapping(value = "/merchant/deleteBatch")
    public Result<CommoditySpuVO> deleteBatch(@RequestBody CommoditySpuVO commoditySpuVO) {
        Result<CommoditySpuVO> result = new Result<CommoditySpuVO>();
        if(StringUtils.isBlank(commoditySpuVO.getIds())){
            return result.error500("参数错误,id为空");
        }
        boolean Statue=iCommoditySpuService.judgeIsVisible(commoditySpuVO.getIds());
        if(!Statue){
            this.iCommoditySpuService.delListBatchMain(Arrays.asList(commoditySpuVO.getIds().split(",")));
            //批量删除商品id与类目id的关系
            relationshipService.deleteListCategoryAndSpuId(Arrays.asList(commoditySpuVO.getIds().split(",")));
            result.success("删除成功!");

        }else {
            result.error500("商品已上架不能执行删除操作!");
        }
        return result;
    }
    @DeleteMapping(value = "/web/deleteBatch")
    public Result<CommoditySpuVO> deleteWebBatch(@RequestParam(name="ids",required=true) String ids) {
        Result<CommoditySpuVO> result = new Result<CommoditySpuVO>();
        if(StringUtils.isBlank(ids)){
            return result.error500("参数错误,id为空");
        }
        boolean Statue=iCommoditySpuService.judgeIsVisible(ids);
        if(!Statue){
            this.iCommoditySpuService.delListBatchMain(Arrays.asList(ids.split(",")));
            //批量删除商品id与类目id的关系
            relationshipService.deleteListCategoryAndSpuId(Arrays.asList(ids.split(",")));
            result.success("删除成功!");

        }else {
            result.error500("商品已上架不能执行删除操作!");
        }
        return result;
    }
    /**
     * 通过id查询----spu
     * @param id
     * @return
     */
    @GetMapping(value = "/merchant/queryById")
    public Result<?> queryById(@RequestParam(name="id") String id) {
        CommoditySpu spu = iCommoditySpuService.getById(id);
        if (spu==null||spu.getDeleted()){
            return Result.error("商品不存在");
        }
        return Result.ok(spu);
    }

    /**
     * 通过goods_id查询spu_id 查询sku
     * @param id
     * @return
     */
    @GetMapping(value = "/merchant/queryItemMainByMainId")
    public Result<List<?>> queryItemMainListByMainId(@RequestParam(name="id",required=true) Long id) {
        Result<List<?>> result = new Result<>();

        List<CommoditySku> itemMainList = iCommoditySkuService.selectByMainId(id);
        result.setResult(itemMainList);
        result.setSuccess(true);
        return result;
    }
    @GetMapping(value = "/web/queryItemMainByMainId")
    public Result<?> queryWebItemMainListByMainId(@RequestParam(name="id",required=true) Long id) {

        List<CommoditySku> itemMainList = iCommoditySkuService.selectByMainId(id);
        return Result.ok(itemMainList);
    }

    /**l
     * 导出excel
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, HttpServletResponse response) {
        // Step.1 组装查询条件
        QueryWrapper<CommoditySpu> queryWrapper = null;
        try {
            String paramsStr = request.getParameter("paramsStr");
            if (oConvertUtils.isNotEmpty(paramsStr)) {
                String deString = URLDecoder.decode(paramsStr, "UTF-8");
                CommoditySpu commoditySpu = JSON.parseObject(deString, CommoditySpu.class);
                queryWrapper = QueryGenerator.initQueryWrapper(commoditySpu, request.getParameterMap());
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        //Step.2 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        List<CommoditySpu> pageList = new ArrayList<>();
        List<CommoditySpu> commoditySpuDTOSList = iCommoditySpuService.list(queryWrapper);
        for (CommoditySpu commoditySpuDTO : commoditySpuDTOSList) {
            CommoditySpu vo = new CommoditySpu();
            BeanUtils.copyProperties(commoditySpuDTO, vo);
            List<CommoditySku> commoditySkuDTOList = iCommoditySkuService.selectByMainId(commoditySpuDTO.getId());
            vo.setProductSkuList(commoditySkuDTOList);
            pageList.add(vo);
        }
        //导出文件名称
        mv.addObject(NormalExcelConstants.FILE_NAME, "商品SPU列表");
        mv.addObject(NormalExcelConstants.CLASS, CommoditySpu.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("商品SPU列表数据", "导出人:Jeecg", "导出信息"));
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<CommoditySpuPageDTO> list = ExcelImportUtil.importExcel(file.getInputStream(), CommoditySpuPageDTO.class, params);
                for (CommoditySpuPageDTO page : list) {
                    CommoditySpu po = new CommoditySpu();
                    BeanUtils.copyProperties(page, po);
                    iCommoditySpuService.saveMain(po, ObjectUtils.copyList(page.getProductSkuList(),CommoditySku.class));
                }
                return Result.ok("文件导入成功！数据行数:" + list.size());
            } catch (Exception e) {
                log.error(e.getMessage(),e);
                return Result.error("文件导入失败:"+e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.ok("文件导入失败！");
    }

    /**
     * 商户端-单个商品的上架下架
     * @param
     * @return
     */
    @PostMapping (value = "/merchant/goodsOneUpperLower")
    public Result<?> goodsUpperShelf(@Valid @RequestBody CommoditySpuDTO commoditySpuDTO,BindingResult bindingResult){
        Result<CommoditySpuVO> result = new Result<CommoditySpuVO>();
        if(bindingResult.hasErrors()){
            return result.error500(JacksonUtils.toJSONString(bindingResult.getAllErrors()));
        }
        CommoditySpu db=iCommoditySpuService.getById(commoditySpuDTO.getId());
        if(db==null){
            return Result.error("商品不存在");
        }
        if (ProductSpuConstants.SPU_NOT_TOEXAMINE.equals(db.getToExamine())){
            return Result.error("商品未通过审核不允许该操作");
        }
        CommonResult<List<ShopDTO>> commonResult= shopService.getListOfStores(JwtUtil.getUserIdByToken());
        List<ShopDTO> shopList=commonResult.isSuccess()?commonResult.getData():Collections.emptyList();
        if (!shopList.stream().anyMatch(a->db.getShopId().equals(a.getId()))){
            return Result.error("该用户没有操作该商品的权限");
        }
        if(spuVisible.equals(commoditySpuDTO.getUpperLowerFlag())){
            if(db.getVisible()){return Result.error("商品已上架，无法在此操作");}else {
                iCommoditySpuService.changeProductSpuVisible(commoditySpuDTO.getId(),true);
                AppMessageDTO appMessageDTO = new AppMessageDTO();
                appMessageDTO.setContent("商品："+db.getName()+"于"+DateUtils.formatDate(new Date())+"上架成功!");
                appMessageDTO.setTitle("商品上架");
                appMessageDTO.setCreator("");
                appMessageDTO.setType(AppMessageTypeEnum.Commodity_Notification.getValue());
                appMessageDTO.setReceiver(JwtUtil.getUserIdByToken());
                appMessageDTO.setTemplateId(1);
                appMessageDTO.setCreateTime(DateUtils.getDate());
                appMessageDTO.setEntitiesId(Long.toString(db.getId()));
                appMessageService.sendAppMessageToUser(appMessageDTO);
            }
        }else{
            if(!db.getVisible()){
                return Result.error("商品已下架，无法在此操作");}else {
                ProductRecommendBO recommendBO=productRecommendService.getProductBySpuId(db.getId());
                if (recommendBO!=null){
                return Result.error("该商品处于推荐位，请联系平台进行处理");
                }
                iCommoditySpuService.changeProductSpuVisible(commoditySpuDTO.getId(),false);
                AppMessageDTO appMessageDTO = new AppMessageDTO();
                appMessageDTO.setContent("商品名称"+db.getName()+"于"+DateUtils.formatDate(new Date())+"商品下架成功");
                appMessageDTO.setTitle("商品下架");
                appMessageDTO.setCreator("");
                appMessageDTO.setType(AppMessageTypeEnum.Commodity_Notification.getValue());
                appMessageDTO.setReceiver(JwtUtil.getUserIdByToken());
                appMessageDTO.setTemplateId(1);
                appMessageDTO.setCreateTime(DateUtils.getDate());
                appMessageDTO.setEntitiesId(Long.toString(db.getId()));
                appMessageService.sendAppMessageToUser(appMessageDTO);
            }
        }
        return result;
    }
    /**
     * 商户端-批量商品的上架下架
     * @param commoditySpuPageVO
     * @return
     */
    @PostMapping(value = "/merchant/goodsListUpperLower")
    public Result<?> goodsLowerShelf(@Valid @RequestBody CommoditySpuPageVO commoditySpuPageVO, BindingResult bindingResult) {
        Result result = new Result<>();
        if(bindingResult.hasErrors()){
            return result.error500(JacksonUtils.toJSONString(bindingResult.getAllErrors()));
        }
        Collection<CommoditySpu> dbList=iCommoditySpuService.listByIds(new ArrayList<>(Arrays.asList(commoditySpuPageVO.getIds().split(splitFlag))));
        if (!dbList.stream().anyMatch(o->ProductSpuConstants.SPU_NOT_TOEXAMINE.equals(o.getToExamine()))){
            return Result.error("存在未审核商品，不允许该操作");
        }
        CommonResult<List<ShopDTO>> commonResult= shopService.getListOfStores(JwtUtil.getUserIdByToken());
        List<ShopDTO> shopList=commonResult.isSuccess()?commonResult.getData():Collections.emptyList();
        if (!dbList.stream().anyMatch(o->shopList.stream().anyMatch(a->o.getShopId().equals(a.getId())))){
            return Result.error("该用户没有操作该商品的权限");
        }
        List<ProductRecommendBO> bos= productRecommendService.getProductRecommendList(null, CommonStatusEnum.ENABLE.getValue());
        if (bos.stream().anyMatch(o->dbList.stream().anyMatch(a->o.getProductSpuId().equals(a.getId())))){
            return Result.error("存在处于推荐位置的商品无法进行批量下架,请联系平台处理");
        }
        String upperLowerFlag = commoditySpuPageVO.getUpperLowerFlag();
        // upperLowerFlag 上下架标识(1：上架，2：下架),上架需要通过审核才可以
        if (spuVisible.equals(upperLowerFlag)) {
            if (dbList.stream().anyMatch(CommoditySpu::getVisible)){
                return Result.error("部分商品已上架，不允许重复操作");
            }
            boolean flag = iCommoditySpuService.batchChangeProductSpuVisible(new ArrayList<>(Arrays.asList(
                    commoditySpuPageVO.getIds().split(",")).stream().map(a->Long.parseLong(a)).collect(Collectors.toList())),true);
            if (flag) {
                result.setSuccess(true);
                result.setMessage("上架成功");
                dbList.stream().map(o->{
                    AppMessageDTO appMessageDTO = new AppMessageDTO();
                    appMessageDTO.setContent("商品"+o.getName()+"于"+DateUtils.formatDate(new Date())+"上架成功!")
                    .setTitle("商品上架")
                    .setCreator("")
                    .setType(AppMessageTypeEnum.Commodity_Notification.getValue())
                    .setReceiver(JwtUtil.getUserIdByToken())
                    .setTemplateId(1)
                    .setCreateTime(DateUtils.getDate())
                    .setEntitiesId(commoditySpuPageVO.getIds());
                    return appMessageService.sendAppMessageToUser(appMessageDTO);
                });

                AppMessageDTO appMessageDTO = new AppMessageDTO();
                appMessageDTO.setContent("批量上架的商品有："+dbList.stream().map(CommoditySpu::getName).collect(Collectors.joining()));
                appMessageDTO.setTitle("商品批量上架");
                appMessageDTO.setCreator("");
                appMessageDTO.setType(AppMessageTypeEnum.Commodity_Notification.getValue());
                appMessageDTO.setReceiver(JwtUtil.getUserIdByToken());
                appMessageDTO.setTemplateId(1);
                appMessageDTO.setCreateTime(DateUtils.getDate());
                appMessageDTO.setEntitiesId(commoditySpuPageVO.getIds());
                appMessageService.sendAppMessageToUser(appMessageDTO);
            } else {
                result.error500("上架失败");
            }
        } else {
            if (dbList.stream().anyMatch( a->!a.getVisible())){
                return Result.error("部分商品已下架，不允许重复操作");
            }
            boolean flag = iCommoditySpuService.batchChangeProductSpuVisible(new ArrayList<>(Arrays.asList(
                    commoditySpuPageVO.getIds().split(",")).stream().map(a->Long.parseLong(a)).collect(Collectors.toList())),false);
            if (flag) {
                result.setSuccess(true);
                result.setMessage("下架成功");
                AppMessageDTO appMessageDTO = new AppMessageDTO();
                appMessageDTO.setContent("批量下架的商品有"+dbList.stream().map(CommoditySpu::getName).collect(Collectors.joining()));
                appMessageDTO.setTitle("商品批量下架");
                appMessageDTO.setCreator("");
                appMessageDTO.setType(AppMessageTypeEnum.Commodity_Notification.getValue());
                appMessageDTO.setReceiver(JwtUtil.getUserIdByToken());
                appMessageDTO.setTemplateId(1);
                appMessageDTO.setCreateTime(DateUtils.getDate());
                appMessageDTO.setEntitiesId(commoditySpuPageVO.getIds());
                appMessageService.sendAppMessageToUser(appMessageDTO);
            } else {
                result.setMessage("下架失败");
            }
        }
        return result;
    }

    /**
     * 商户端--商户获取店铺的所有商品
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping(value = "/merchant/getGoodsInformation")
    public Result<?> getAllGoodsInformation(CommoditySpuVO vo, @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                            @RequestParam(name="pageSize", defaultValue="10") Integer pageSize, HttpServletRequest req){
        if(StringUtils.isBlank(vo.getShopId())){
            return Result.error("参数错误,shopId为空!");
        }
        vo.setDeleted(false);
        QueryWrapper<CommoditySpu> queryWrapper = QueryGenerator.initQueryWrapper(ObjectUtils.copyObject(vo,CommoditySpu.class), req.getParameterMap());

        //添加查询条件---查询所有未删除
        Page page = new Page<>(pageNo, pageSize);
        IPage<?> pageList = iCommoditySpuService.getShopPageListOfShop(page, vo.getShopId(),vo.getEntryId());
        IPage temp=new Page();
        temp.setTotal(pageList.getTotal());
        temp.setCurrent(pageList.getCurrent());
        temp.setSize(pageSize);
        List<CommoditySpuDTO> commoditySpuDTOS=pageList.getRecords().stream().map(o->{CommoditySpuDTO dto=new CommoditySpuDTO();BeanUtils.copyProperties(o,dto);return dto;}).collect(Collectors.toList());
        List<ProductSpuVO> productSpuVOS=CommoditySpuConvert.INSTANCE.convert7(commoditySpuDTOS);
        temp.setRecords(productSpuVOS)       ;
        return Result.ok(temp);

    }

    /**
     * 商城端--获取某个店铺的所有商品
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping(value = "/app/getGoodsInformation")
    public Result<IPage<?>> getAppointGoodsInformation(CommoditySpuPageDTO commoditySpuPageDTO,
                                                       @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                                       @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                                       HttpServletRequest req){
        Result<IPage<?>> result = new Result();
        if(StringUtils.isBlank(commoditySpuPageDTO.getShopId())){
            return result.error500("参数错误,shopId为空!");
        }
        commoditySpuPageDTO.setToExamine("1").setVisible(true).setDeleted(false);
        QueryWrapper<CommoditySpu> queryWrapper = QueryGenerator.initQueryWrapper(ObjectUtils.
                copyObject(commoditySpuPageDTO,CommoditySpu.class), req.getParameterMap());
        //添加查询条件---查询所有未删除
        Page page = new Page<>(pageNo, pageSize);
        IPage<CommoditySpu> temp = iCommoditySpuService.getAppShopPageListOfShop(page, commoditySpuPageDTO.getShopId(),commoditySpuPageDTO.getEntryId());
        IPage<ProductSpuVO> pageList=new Page<>();
        List<CommoditySpu> list=temp.getRecords();
        List<CommoditySpuVO> spuVOList=list.stream().map(o-> CommoditySpuConvert.INSTANCE.convert2(o)).collect(Collectors.toList());
        List<ProductSpuVO> productSpuVOS=CommoditySpuConvert.INSTANCE.convert6(spuVOList);
        pageList.setRecords(productSpuVOS);
        pageList.setPages(temp.getPages());
        pageList.setTotal(temp.getTotal());
        pageList.setCurrent(temp.getCurrent());
        result.setResult(pageList);
        result.setSuccess(true);
        return  result;
    }
    /**
     * 商户端--通过spuid获取单个商品的信息，spu+ 一到多个sku
     * @param id
     * @return
     */
    @GetMapping(value = "/merchant/getOneGoodsInformation")
    public Result<?> getOneGoodsInformation(@RequestParam(name="id",required=true)  Long id){
        if(StringUtils.isBlank(Long.toString(id))){
            return Result.error("参数错误,id为空!");
        }
        ProductMsg productMsg=iCommoditySpuService.getOneShopDetails(id);
        if (productMsg==null){
            return Result.error("商品不存在");
        }
        CommonResult<ShopCategoryDTO> commonResult=relationshipService.getOneShopCategoryBySpuId(productMsg.getId());
        if (commonResult.isSuccess()&&commonResult.getData()!=null){
            productMsg.setEntryId(commonResult.getData().getCategoryId());
            productMsg.setEntryName(commonResult.getData().getCategoryName());
        }
        CommonResult<ShopDTO> shopDTOCommonResult=shopService.getOneShopInfoByShopId(productMsg.getShopId());
        productMsg.setShopName(shopDTOCommonResult.getData().getShopName());
        ProductSpuVO productSpuVO = CommoditySpuConvert.INSTANCE.convert8(productMsg);
        CommonResult<ShopDTO> shopName= shopService.getOneShopInfoByShopId(productSpuVO.getShopId());
        productSpuVO.setShopName(shopName.getData().getShopName());
        return Result.ok(productSpuVO);
    }

    /**
     * 商城端--通过spuid获取单个商品的信息，spu+ 一到多个sku
     * @param id
     * @return
     */
    @GetMapping(value = "/app/getOneGoodsInformation")
    public Result<?> getAppointOneGoodsInformation(@RequestParam(name="id",required=true)  long id){
        Result<ProductSpuVO> result = new Result<>();
        if(StringUtils.isBlank(Long.toString(id))){
            return result.error500("参数错误,id为空!");
        }
        ProductMsg productMsg=iCommoditySpuService.getOneShopDetails(id);
        if (productMsg==null){
            return Result.error("商品不存在");
        }
        result.setResult(CommoditySpuConvert.INSTANCE.convert8(productMsg));
        result.setSuccess(true);
        return result;
    }
    /**
     * 查询商店条目下包含的商店信息(上架的，未删除的，通过审核的)
     * @param categoryId
     * @param shopId
     * @return
     */
    @GetMapping("/merchant/queryGoodsItems")
    public Result queryGoodsItemsByCategoryIdAndShopId(@RequestParam(value = "categoryId",required = true) String categoryId,@RequestParam(value = "shopId",required = true) String shopId){
        Result result = new Result();
        if(categoryId == null || StringUtils.isEmpty(categoryId)|| shopId == null ||StringUtils.isEmpty(shopId) ){
            return Result.error("参数不合法，条目及商铺ID不可为空！");
        }
        try{
            List<Long> spuIds = categoryService.querySpuIdsByCategoryIdAndShopId(categoryId, shopId);
            if(spuIds == null || spuIds.isEmpty() || spuIds.size() == 0){
                result.error500("该条目下没有数据");
                return result;
            }
            List<ProductMsg> goodsList = iCommoditySpuService.getGoodsList(spuIds);
            result.setCode(200);
            result.setResult(goodsList);
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return Result.error("查询出错！");
        }
        return result;
    }


    @GetMapping("/app/getSkuInfo")
    public Result<?> getSkuInfo(@RequestParam Long id){

        ProductMsg productMsg=iCommoditySpuService.getOneShopDetailsBySkuId(id);

        if (productMsg==null){
            return Result.error("信息不存在");
        }
        SkuInfoVo skuInfoVo=new SkuInfoVo();
        CommonResult<ShopDTO> result=shopService.getOneShopInfoByShopId(productMsg.getShopId());
        if (result.getSuccess()){
            skuInfoVo.setShopName(result.getData().getShopName());
        }
        skuInfoVo.setSpuName(productMsg.getName());
        skuInfoVo.setSellerId(productMsg.getSellerId());
        CommoditySkuVO skuVO=ObjectUtils.copyObject(productMsg.getProductSkuList().stream().filter(a->id.equals(a.getId()))
                .findFirst().orElse(new CommoditySkuDTO()),CommoditySkuVO.class);
        skuInfoVo.setSkuDetail(skuVO);

        return Result.ok(skuInfoVo);
    }

    void initProductSku(List<CommoditySku> skus,Long spuId){
        for (CommoditySku temp:skus){
            temp.setDeleted(0);
            temp.setSpuId(spuId);
            temp.setId(GeneratorSnowFlakeIDUtils.nextId());
            temp.setStatus(CommonStatusEnum.DISABLE.getValue());
            temp.setCreateTime(new Date());
        }
    }
    void initProductSpu(CommoditySpu spu){
        spu.setId(GeneratorSnowFlakeIDUtils.nextId());
        spu.setToExamine(ProductSpuConstants.SPU_NOT_TOEXAMINE);
        spu.setSellerId(JwtUtil.getUserInfoByToken().getUserId());
        spu.setVisible(false);spu.setDeleted(false);
        spu.setCreateTime(new Date());
    }
    void initProductWebSpu(CommoditySpu spu){
        spu.setId(GeneratorSnowFlakeIDUtils.nextId());
        spu.setToExamine(ProductSpuConstants.SPU_NOT_TOEXAMINE);
        String sellerId=iCommoditySpuService.getSellerId(spu.getShopId());
        spu.setSellerId(sellerId);
        spu.setVisible(false);spu.setDeleted(false);
        spu.setCreateTime(new Date());
    }
}
